"""
get_h3c_filestorage_quota()函数负责调用华三存储api，将查询结果传入handle_data()函数，然后将数据发送到后端api。适用于E3361版本
"""
# -*- coding:utf-8 -*-


import requests
import datetime
import logging
import json
import re

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s : %(levelname)s : %(message)s',
    filename="/home/storage_api.log"
)


# 提取当前时间，整理格式后返回当前时间值，用于生成result_txt
def result_txt_time():
    now = datetime.datetime.now()
    now_time = now.strftime("%Y%m%d%H%M")
    return now_time


# 调用华三集群的API，返回存储目录及使用情况
def get_h3c_filestorage_quota():
    # 拼接成登陆url
    base_url = "http://地址/"
    request_url = "api/v1/auth/login"
    url = base_url + request_url

    # 登陆用户名、密码
    data = {"username": "xx", "password": "xx"}

    # 登录请求
    res = requests.post(url=url, data=json.dumps(data), headers={'content-type': "application/json"})

    # 从响应头信息中提取后面访问需要的cookie_value和x_xsrf_token_value
    XSRF_TOKEN = res.cookies.get_dict().get('XSRF-TOKEN')
    calamari_sessionid = res.cookies.get_dict().get('calamari_sessionid')
    Cookie = 'XSRF-TOKEN=' + XSRF_TOKEN +';' + 'calamari_sessionid=' + calamari_sessionid

    # 获取集群ID
    cluster_id_api_url = "/api/v3/plat/cluster"
    cluster_id_url = base_url + cluster_id_api_url
    cluster_res = requests.get(
        url=cluster_id_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': XSRF_TOKEN,
            'Cookie': Cookie,
        })

    cluster_data = cluster_res.json()
    cluster_id = cluster_data['data']['id']

    # 生成请求URL
    filestorage_quota_url_1 = "/api/v3/onestor/"
    filestorage_quota_url_2 = "/filestorage/quota"
    filestorage_quota_url_3 = "?sort_key=&sort_order=&param_version=1&offset=0&limit=50&key_word=&quota_type=0&language=zh-cn"
    filestorage_quota_url = base_url + filestorage_quota_url_1 + cluster_id + filestorage_quota_url_2 + filestorage_quota_url_3

    # 发送GET请求，得到返回数据
    filestorage_quota_res = requests.get(
        url=filestorage_quota_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': XSRF_TOKEN,
            'Cookie': Cookie,
        })
    filestorage_quota_data = filestorage_quota_res.json()

    # logout登出
    logout_api_url = "/api/v1/auth/logout"
    logout_url = base_url + logout_api_url
    logout_res = requests.get(
        url=logout_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': XSRF_TOKEN,
            'Cookie': Cookie,
        })
    return filestorage_quota_data


# 使用POST协议将数据发送到对端接口
def send_data_to_api(ip, path, assigned_volume, use_volume, residue_volume):
    
    base_url = "https://地址"

    # request_data格式
    request_data = {
        "ip": ip,
        "path": path,
        "assigned_volume": assigned_volume,
        "use_volume": use_volume,
        "residue_volume": residue_volume
    }

    # 使用POST协议发送数据，并接收返回值
    requests_res = requests.post(
        url=base_url,
        data=json.dumps(request_data)
    )
    requests_res_data = requests_res.json()
    # 记录日志
    logging.info("execute send_data_to_api path: {0} result: {1}".format(path, requests_res_data))
    return requests_res_data


# 接收调用华三存储API得到的数据，整理每个目录数据的格式，然后调用send_data_to_api()函数发送数据至后端接口，存入数据库
def handle_data(dict_data):
    lists_dict_data = dict_data['data']['quota_list']
    # 生成日志，记录整理后准备发送的数据
    result_txt_name = "/home/h3c_log_" + result_txt_time() + ".txt"
    with open(result_txt_name, "w") as log:
        tplt = "{:<10}\t{:<10}\t{:<10}\t{:<10}\t{:<10}"
        log.write(tplt.format('ip', 'path', 'assigned_volume(G)', 'use_volume(G)', 'residue_volume(G)', chr(255)))
        log.write('\n')
        for list_dict_data in lists_dict_data:
            ip = "xx"
            path = list_dict_data['path'][1:]
            assigned_volume = round(list_dict_data['bhard_threshold'][1] / 1024 / 1024 / 1024, 3)
            use_volume = round(list_dict_data['bused'][1] / 1024 / 1024 / 1024, 3)
            residue_volume = round(list_dict_data['bfree'][1] / 1024 / 1024 / 1024, 3)

            try:
                log.write(tplt.format(ip, path, assigned_volume, use_volume, residue_volume, chr(255)))
                log.write('\n')
                logging.info("execute write path ({0}) successful".format(path))
                send_data_to_api(ip, path, assigned_volume, use_volume, residue_volume)
            except:
                log.write("error\n")
                logging.error("execute write path ({0}) error".format(path))


if __name__ == '__main__':
    h3c_sjq_dict_data = get_h3c_filestorage_quota()
    handle_data(h3c_sjq_dict_data)
